<?php
class Bookmark {
    private $conn;

    public function __construct($db) {
        $this->conn = $db;
    }

    public function getAll() {
        $query = "SELECT id, title, url, category, imgurl, description FROM bookmarks ORDER BY category, title";
        $result = $this->conn->query($query);
        return $result->fetch_all(MYSQLI_ASSOC);
    }

    public function getAllCategories() {
        $query = "SELECT DISTINCT category FROM bookmarks ORDER BY category";
        $result = $this->conn->query($query);
        return $result->fetch_all(MYSQLI_ASSOC);
    }

    public function create($title, $url, $category, $imgurl, $description) {
        if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
            $url = "http://" . $url;
        }
        $query = "INSERT INTO bookmarks (title, url, category, imgurl, description) VALUES (?, ?, ?, ?, ?)";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("sssss", $title, $url, $category, $imgurl, $description);
        return $stmt->execute();
    }
    
    public function updateImgUrl($id, $imgurl) {
        $query = "UPDATE bookmarks SET imgurl = ? WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("si", $imgurl, $id);
        return $stmt->execute();
    }

    public function update($id, $title, $url, $category, $description, $imgurl) {
        $query = "UPDATE bookmarks SET title = ?, url = ?, category = ?, description = ?, imgurl = ? WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("sssssi", $title, $url, $category, $description, $imgurl, $id);
        return $stmt->execute();
    }

    public function delete($id) {
        $query = "DELETE FROM bookmarks WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("i", $id);
        return $stmt->execute();
    }

    public function getById($id) {
        $query = "SELECT * FROM bookmarks WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc();
    }

}